const multer = require("multer")
const path = require("path")


//封装处理路径函数
const handlePath = (dir) => {
  return path.join(__dirname, './', dir)
}

//设置multer的配置对象
const storage = multer.diskStorage({
  //存储路径
  destination: function (req, file, cb) {
    if (file.mimetype === "image/jpeg" || file.mimetype === "image/png" || file.mimetype === "image/webp" || file.mimetype === "image/jpg") {
      cb(null, handlePath("../public"))
    } else {
      cb({ error: "仅支持 jpg/png/webp 格式的图片！" })
    }
  },
  //存储的名称
  filename: function (req, file, cb) {
    //图片名称分割为数组，截取后缀
    const fileFormat = file.originalname.split('.')
    //自定义图片名称
    cb(null, Date.now() + '.' + fileFormat[fileFormat.length - 1])
  }

})

//为multer添加配置
const multerConfig = multer({
  storage: storage,
  limits: { fileSize: 2097152 }//2M
})

module.exports = multerConfig